import classNames from 'classnames'
import { useDispatch } from 'react-redux'
import { useRef, useState, useEffect } from 'react'
import {
  todoDel,
  updateTodoName,
  updateTodoStatus,
} from '../store/actions/todo'
export default function TodoItem({ item }) {
  const inputRef = useRef()
  const dispatch = useDispatch()
  const [editId, setEditId] = useState('')
  const [currentName, setCurrentName] = useState('')
  const handleDelete = (id) => dispatch(todoDel(id))
  const handleUpdateTodoStatus = (id) => dispatch(updateTodoStatus(id))
  // 双击显示编辑框
  const handleDblClick = (id) => handleBlur(id, item.name)
  const handleBlur = (id, name) => {
    setEditId(id)
    setCurrentName(name)
  }
  const handleKeyUp = (e) => {
    if (e.key === 'Escape') return handleBlur('', '')
    // 把 currentName 更新 Redux 中对应的那一条的 name
    if (e.key === 'Enter') {
      if (currentName.trim().length === 0) return alert('不能为空')
      dispatch(updateTodoName(item.id, currentName))
      // 隐藏编辑框
      handleBlur('', '')
    }
  }
  useEffect(() => {
    if (editId === '') return
    inputRef.current.focus()
  }, [editId])
  return (
    <li
      className={classNames({
        completed: item.done,
        editing: editId === item.id,
      })}
    >
      <div className='view'>
        <input
          className='toggle'
          type='checkbox'
          checked={item.done}
          onChange={() => handleUpdateTodoStatus(item.id)}
        />
        <label onDoubleClick={() => handleDblClick(item.id)}>{item.name}</label>
        <button
          className='destroy'
          onClick={() => handleDelete(item.id)}
        ></button>
      </div>
      {/* 做编辑用的 */}
      <input
        className='edit'
        onChange={(e) => setCurrentName(e.target.value)}
        ref={inputRef}
        onBlur={handleBlur}
        value={currentName}
        onKeyUp={handleKeyUp}
      />
    </li>
  )
}
